package org.example.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.example.dao.FoodDao;
import org.example.model.Features;
import org.example.model.Food;
import org.example.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
// 这个注解表示这是一个服务类，并且在事务中进行操作，如果出现异常，则回滚事务
@Transactional(rollbackFor = Exception.class)
public class FoodService {
    @Autowired
    private FoodDao foodDao;


    public PageInfo<Food> getFoodList(Food foods) {
        PageHelper.startPage(foods.getPageNo(), foods.getPageSize());
        List<Food> foodList = foodDao.getFoodList(foods);
        List<Features> featuresList = foodDao.foodFeatures();
        Iterator<Food> iterator = foodList.iterator();
        while (iterator.hasNext()) {
            Food next = iterator.next();
            List<String> featureList = new ArrayList<>();
            for (Features features : featuresList) {
                if (next.getId() == features.getFoodId()) {
                    featureList.add(features.getName());
                }
            }
            next.setFeatures(featureList);
        }
        System.out.println(foods.getPageSize());
        PageInfo<Food> pageInfo = new PageInfo<>(foodList);
        System.out.println(pageInfo.getPageSize());
        return pageInfo;
    }


    public List<Features> feature() {
        List<Features> featureList = foodDao.foodFeatures2();
        return featureList;
    }

    public Food addFood(Food food) {
        //查重
        if (foodDao.getFoodId(food.getName())!=null) {
            System.out.println("食物已存在");
            return null;
        }else{
            System.out.println("食物不存在");
            //添加食物数据
            System.out.println(food.toString());
            foodDao.addFood(food);
            //添加食物特征数据
            System.out.println(food.getId());
            System.out.println(food.getFeatureId());
            Integer[] featuresList = food.getFeatureId();
            for (Integer features : featuresList) {
                foodDao.addFoodFeatures( features,food.getId());
            }
            return food;
        }


    }

    public boolean deleteFood(int id) {
        //删除食物数据
        if (foodDao.deleteFood(id) == 1) {
            //删除食物特征数据
            foodDao.deleteFoodFeatures(id);
            return true;
        } else {
            return false;
        }
    }


}
